package org.wzl.databasesync.utils;

import lombok.extern.slf4j.Slf4j;
import org.wzl.databasesync.dto.DatabaseInfo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class JdbcUtils {

    private static final String DRIVER_CLASS = "com.mysql.cj.jdbc.Driver";

    static {
        try {
            Class.forName(DRIVER_CLASS);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Failed to load JDBC driver", e);
        }
    }

    public static Connection getConnection(DatabaseInfo databaseInfo) throws SQLException {
        String url = String.format("jdbc:mysql://%s:%s/%s", databaseInfo.getUrl(), databaseInfo.getPort(), databaseInfo.getSelectDatabaseName());
        return DriverManager.getConnection(url, databaseInfo.getUsername(), databaseInfo.getPassword());
    }

    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(Connection conn, Statement stmt) {
    }

    public static List<String> executeQuery(DatabaseInfo databaseInfo, String sql) throws SQLException {
        List<String> result = new ArrayList<>();
        try (Connection conn = getConnection(databaseInfo);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {

            int columnCount = rs.getMetaData().getColumnCount();
            while (rs.next()) {
                StringBuilder row = new StringBuilder();
                for (int i = 1; i <= columnCount; i++) {
                    row.append(rs.getString(i)).append("\t");
                }
                result.add(row.toString().trim());
            }
        } catch (SQLException e) {
            log.error("Failed to execute query", e);
            throw e;
        }
        return result;
    }
}